package com.huatai.auth.service;

import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.huatai.common.api.R;
import com.huatai.common.util.Func;
import com.huatai.common.util.ObjectUtil;
import com.huatai.common.util.StringUtil;
import com.huatai.common.util.WebUtil;
import com.huatai.user.feign.UserClient;
import com.huatai.user.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.UnauthorizedUserException;
import org.springframework.security.oauth2.common.exceptions.UserDeniedAuthorizationException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @program: ht-system
 * @description: 用户登录详情
 * @author: songxiude
 * @create: 2023-02-07 10:47
 **/
@Service
//@RefreshScope
public class HtUserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private UserService userService;

	@Value("${captcha.open}")
	//@NacosValue(value = "${captcha.open}",autoRefreshed = true)
	private boolean open;

	@Autowired
	private StringRedisTemplate redisTemplate;


	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//判断软件授权是否已授权
//		Map<String, ValidateResult> validate = LicenseManager.validate();
//		ValidateResult validateResult = validate.get("Authorize");
//		if (validateResult.getCode().intValue()!=200) {
//			throw new RuntimeException("{code:"+validateResult.getCode()+",message:"+validateResult.getMessage()+"}");
//		}

		//判断是否开启验证码验证
		if (open) {
			HttpServletRequest request = WebUtil.getRequest();
			String captchaKey = request.getHeader("Captcha-Key");
			String captchaCode = request.getHeader("Captcha-Code");
			String code = redisTemplate.opsForValue().get("ht:captcha:" + captchaKey);
			// 判断验证码
			if (captchaCode == null || !StringUtil.equalsIgnoreCase(captchaCode, code)) {
				throw new InvalidGrantException("验证码错误");
			}
		}


		UserVo userVo = userService.getUserInfo(username);

		//判断用户是否已经登录
//		String redistoken = redisTemplate.opsForValue().get("ht:token:" + userVo.getId());
//		if (StringUtil.isNotBlank(redistoken)) {
//			throw new InvalidGrantException("该用户已在别处登录，不可重复登录");
//		}

//		if (ObjectUtil.isEmpty(userVo)) {
//			throw new UsernameNotFoundException("用户名或密码错误");
//		}

		if (ObjectUtil.isEmpty(userVo)) {
			throw new InvalidGrantException("用户名或密码错误");
		}
		if(userVo.getStatus().intValue()==1){
			throw new InvalidGrantException("用户已禁用");
		}
		//判断客户端用户是否审核通过
		if (userVo.getUserType().intValue() == 2 && userVo.getCheckState().intValue() == 0) {
			throw new InvalidGrantException("该用户正在审核中，请耐心等待");
		}
		//判断用户是否审核不通过
		if (userVo.getUserType().intValue() == 2 && userVo.getCheckState().intValue() == 2) {
			throw new InvalidGrantException("该用户资料审核不通");
		}
		List<String> permissions = userVo.getPermissions();

//		if(CollectionUtils.isEmpty(permissions) || permissions.size()==0){
//			throw new InvalidGrantException("用户无权限");
//		}


		//封装返回UserDetails
		return new HtUserDetails(userVo.getId(), userVo.getCode(), userVo.getName(),
			userVo.getRealName(), userVo.getAvatar(), userVo.getIsAdmin(), userVo.getDeptId(), userVo.getPostId(), userVo.getSkin(),
			username, userVo.getPassword(), true, true, true, true,
			AuthorityUtils.commaSeparatedStringToAuthorityList(Func.join(permissions)));
	}
}
